/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller.c;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.Enum.PayStatusEnum;
import com.ykht.proj.activity.dto.CnActivityOrderDTO;
import com.ykht.proj.activity.entity.CnActivityConsumeRecord;
import com.ykht.proj.activity.entity.CnActivityOrder;
import com.ykht.proj.activity.entity.CnActivityPersonShop;
import com.ykht.proj.activity.mq.MqConfig;
import com.ykht.proj.activity.mq.producer.ScheduledMsgProducer;
import com.ykht.proj.activity.service.CnActivityConsumeRecordService;
import com.ykht.proj.activity.service.CnActivityOrderService;
import com.ykht.proj.activity.service.CnActivityPersonShopService;
import com.ykht.proj.activity.service.CnActivityShopService;
import com.ykht.proj.activity.vo.ActivityOrderVo;
import com.ykht.proj.activity.vo.CnActivityPersonShopVo;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.annotation.Inner;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.comsrv.api.feign.RemoteQRCodeService;
import com.ykht.proj.coupon.vo.AboutShopVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 活动订单表
 *
 * @author csg
 * @date 2020-12-23 11:13:32
 */
@RestController
@AllArgsConstructor
@RequestMapping("c/order")
@Api(value = "cnactivityorder", tags = "c端活动订单相关")
@Slf4j
public class ActivityOrderController {

	private final CnActivityConsumeRecordService cnActivityConsumeRecordService;

	private final CnActivityOrderService cnActivityOrderService;
	private final RemoteQRCodeService remoteQRCodeService;

	private final CnActivityPersonShopService cnActivityPersonShopService;
	private final CnActivityShopService cnActivityShopService;

	@ApiOperation(value = "订单列表", notes = "订单列表")
	@GetMapping("/page")
	public R<Page<CnActivityOrder>> getCnActivityOrderPage(Page page, String status) {

		String[] sta = null;
		if (StringUtils.isNotBlank(status)) {
			sta = status.split(",");
		}
		return R.ok(cnActivityOrderService.page(page, Wrappers.lambdaQuery(CnActivityOrder.class)
				.eq(CnActivityOrder::getPersonId, SecurityUtils.getPersonId())
				.in(StringUtils.isNotBlank(status), CnActivityOrder::getPayStatus, sta)
				.orderByDesc(CnActivityOrder::getCreateTime)));
	}

	@ApiOperation(value = "通过id查询订单详情", notes = "通过id查询订单详情")
	@GetMapping("/{id}")
	public R<ActivityOrderVo> getById(Page page, @PathVariable("id") Long id, String longitude, String latitude) {
		return cnActivityOrderService.getOrderById(page, id, longitude, latitude);
	}


	@ApiOperation(value = "结算生成订单", notes = "结算生成订单")
	@GetMapping("create/{id}")
	public R order(@PathVariable("id") Long activityId, @RequestParam("shopIds") String shopIds) {
		log.info("->结算生成订单,activityId:	{},shopIds:{}", activityId, shopIds);
		if (StrUtil.isBlank(shopIds)) {
			return R.failed();
		}
		return cnActivityOrderService.order(activityId, shopIds);
	}

	@Resource
	private ScheduledMsgProducer scheduledMsgProducer;
	@Resource
	private MqConfig mqConfig;

	@ApiOperation(value = "结算生成订单", notes = "结算生成订单")
	@GetMapping("mq/{id}")
	@Inner(false)
	public R order1(@PathVariable("id") String order) {
		try {
		/*	redisTemplate.opsForHash().put(CacheConstants.USER_DETAILS_ACTIVITYORDERID_PREPAYID,"1","2");
			Object id = redisTemplate.opsForHash().get(CacheConstants.USER_DETAILS_ACTIVITYORDERID_PREPAYID,"1");
			redisTemplate.expire(CacheConstants.USER_DETAILS_ACTIVITYORDERID_PREPAYID,2, TimeUnit.HOURS);
			System.out.println(id);*/
			System.out.println(mqConfig.toString());
			scheduledMsgProducer.sendOrderScheduledMsg(order, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok();
    }
    @ApiOperation(value = "微信公众号服务器配置接口", notes = "结算生成订单")
    @GetMapping("testApi")
	@Inner(false)
	public String order21(String signature, String timestamp, String nonce, String echostr) {
//			System.out.println(RandomUtil.randomString(32));;
		String token = "5dn4frcsfta6lvivuhgi89q43s5x9kj1";
		Map<String, String> map = new TreeMap();
		map.put("token", token);
		map.put("timestamp", timestamp);
		map.put("nonce", nonce);
		String str = "";
		for (Map.Entry<String, String> entry : map.entrySet()) {
			str += entry.getValue();
		}

		String tempSign = DigestUtil.sha1Hex(str);
		log.info("->组装签名结果：{}", tempSign);
		log.info("->参数signature：{}", signature);

		if (signature.equals(tempSign)) {
			return echostr;
		} else {
			return null;
		}
	}

	/*public static void main(String[] args) {
		Map<String,String> map = new TreeMap();
		String token = "5dn4frcsfta6lvivuhgi89q43s5x9kj1";
		map.put("token",token);
		map.put("timestamp","timestamp");
		map.put("nonce","nonce");
		String str = "";

		for (Map.Entry<String,String> entry : map.entrySet()) {
			str+=entry.getValue();
		}
		System.out.println(str);
		System.out.println(DigestUtil.sha1Hex(str));
		System.out.println(RandomUtil.randomString(32));;

		AES aes = new AES(Mode.CTS, Padding.PKCS5Padding, "0CoJUm6Qyw8W8jud".getBytes(), "0102030405060708".getBytes());
	}*/

	@ApiOperation(value = "取消订单")
	@GetMapping("cancel/{orderId}")
	public R cancelOrder(@PathVariable("orderId") Long orderId) {
		log.info("->取消订单,id:	{}", orderId);
		return cnActivityOrderService.cancelOrder(orderId);
	}

	@ApiOperation(value = "支付订单")
	@GetMapping("pay/{orderId}")
	public R pay(@PathVariable("orderId") Long orderId) {
		log.info("->支付订单,id:	{}", orderId);
		return cnActivityOrderService.pay(orderId);
	}

	@ApiOperation(value = "微信异步回调")
	@PostMapping("callback")
	@Inner(false)
	public R callback(@RequestBody String data, HttpServletRequest request) {
		log.info("->支付回调request:{}", request);
		log.info("->支付回调data:{}", data);
		return cnActivityOrderService.callback(data, request);
	}

	@ApiOperation(value = "支付订单状态获取")
	@GetMapping("status")
	@Inner(false)
	public R orderStatus() {
		log.info("->支付订单状态获取");
		List<Map<String, Object>> list = new ArrayList<>();
		for (PayStatusEnum temp : PayStatusEnum.values()) {
			Map map = new HashMap();
			map.put("value", temp.getValue());
			map.put("desc", temp.getDesc());
			list.add(map);
		}
		return R.ok();
	}


	/**
	 * 我的卡包
	 *
	 * @return
	 */
	@ApiOperation(value = "我的卡包", notes = "我的卡包")
	@GetMapping("/getCardPacakgePageList")
	public R getCardPacakgePageList(Page page) {
		QueryWrapper<CnActivityOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(CnActivityOrder::getPayStatus, PayStatusEnum.PAY.getValue())
				.eq(CnActivityOrder::getPersonId, SecurityUtils.getPersonId())
				.orderByAsc(CnActivityOrder::getPastStatus).orderByDesc(CnActivityOrder::getPayTime);
		return R.ok(cnActivityOrderService.page(page, queryWrapper));
	}

	@ApiOperation(value = "生成小程序二维码")
	@PostMapping("/QRcode")
	public R QRcode(@RequestBody CnActivityOrderDTO req) {
		try {
			return remoteQRCodeService.QRcode((req.getVerificationCode() + "vip"), "pages/manual/manual");
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
	}

	/**
	 * 会员卡 使用记录
	 *
	 * @return
	 */
	@ApiOperation(value = "会员卡 使用记录", notes = "会员卡 使用记录")
	@GetMapping("/getUsageRecord")
	public R getUsageRecord(Page page, Long orderId) {
		return R.ok(cnActivityConsumeRecordService.page(page, new QueryWrapper<CnActivityConsumeRecord>()
				.lambda().eq(CnActivityConsumeRecord::getOrderId, orderId)
				.eq(CnActivityConsumeRecord::getPersonId, SecurityUtils.getPersonId())));
	}

	/**
	 * 会员卡 相关详情
	 *
	 * @param page      分页
	 * @param orderId   订单ID
	 * @param longitude 经纬度
	 * @param latitude  经纬度
	 * @return
	 * @Inner(false)
	 */
	@ApiOperation(value = "会员卡 相关详情", notes = "会员卡 相关详情")
	@GetMapping("/getUsageDetails")
	public R getUsageDetails(Page page, Long orderId, String longitude, String latitude) {
		// 获取门店剩余次数
		Page<CnActivityPersonShop> personShopPage = cnActivityPersonShopService.page(page, new QueryWrapper<CnActivityPersonShop>()
				.lambda().eq(CnActivityPersonShop::getOrderId, orderId)
				.eq(CnActivityPersonShop::getPerId, SecurityUtils.getPersonId()));
		HashMap<String, Object> hashMap = new HashMap<>();
		if (personShopPage.getRecords().size() > 0) {
			// 获取门店ID集合
			List<Long> ids = new ArrayList<>();
			personShopPage.getRecords().stream().forEach(itme -> {
				ids.add(itme.getShopId());
			});
			// 获取门店的数据
			IPage<AboutShopVo> shopVoPage = cnActivityShopService.AboutShopVoPage(page, ids, longitude, latitude);
			// 把门店数据克隆到 CnActivityPersonShopVo 对象
			List<CnActivityPersonShopVo> activityPersonShopVoList = new ArrayList<>();
			shopVoPage.getRecords().stream().forEach(itme -> {
				activityPersonShopVoList.add(BeanUtil.toBean(itme, CnActivityPersonShopVo.class));
			});
			// 克隆后的对象 去添加每个门店 用户剩余的次数
			activityPersonShopVoList.stream().forEach(itme -> {
				personShopPage.getRecords().stream().forEach(itme1 -> {
					if (itme1.getShopId().equals(itme.getShopId())) {
						itme.setUsageTimes(itme1.getUsageTimes());
						itme.setEndTime(itme1.getEndTime());
					}
				});
			});
			// 吧分页的参数克隆
			IPage<CnActivityPersonShopVo> toBean = BeanUtil.toBean(shopVoPage, Page.class);
			// 把无效的门店安照失效时间 倒叙
			List<CnActivityPersonShopVo> activityPersonShopVoList1 = new ArrayList<>();
			List<CnActivityPersonShopVo> activityPersonShopVoList2 = new ArrayList<>();
			activityPersonShopVoList.stream().forEach(itme -> {
				if (itme.getUsageTimes().equals(0)) {
					activityPersonShopVoList2.add(itme);
				} else {
					activityPersonShopVoList1.add(itme);
				}
			});
			List<CnActivityPersonShopVo> activityPersonShopVoList3 = new ArrayList<>();
			if (activityPersonShopVoList2.size() > 0) {
				activityPersonShopVoList2.sort((m1, m2) -> m2.getEndTime().compareTo(m1.getEndTime()));
			}
			activityPersonShopVoList3.addAll(activityPersonShopVoList1);
			activityPersonShopVoList3.addAll(activityPersonShopVoList2);
			toBean.setRecords(activityPersonShopVoList3);
			hashMap.put("toBean", toBean);
			hashMap.put("order", cnActivityOrderService.getById(orderId));
		}
		return R.ok(hashMap);
	}

}
